<template>
  <div class="app-container calendar-list-container" style="display: flex;">
    <!--左-->
    <div style="flex: 3;overflow-x: auto;margin-right: 10px;padding-right:10px;border-right: 1px dashed #8c939d;">
      <div class="filter-container">
        <el-row>
          <el-col :span="10">
            <!--<el-button type="primary" size="small" @click="updateStatus('Y')">领取合格证书</el-button>-->
            <!--<el-button type="primary" size="small" @click="updateStatus('N')">发放合格证书</el-button>-->
            <!--<el-button type="primary" size="small" @click="giveOrReceiveClick">收放合格证书</el-button>-->
            <el-button type="primary" size="small" @click="exportExcel" :loading="downloadLoading">导出</el-button>
          </el-col>
          <el-col :span="14" style="text-align: right">
            <el-input size="small" style="width: 200px" class="filter-item fsc-search" placeholder="输入车架号,回车查询"
                      v-model="listQuery.condition.vin" @keyup.enter.native="searchClick"></el-input>
            <!--搜索-->
            <el-button class="filter-item" size="small" type="primary" v-waves icon="el-icon-search" @click="search">搜索</el-button>
            <el-button class="filter-item" size="small" type="primary" v-waves icon="el-icon-circle-plus-outline"
                       @click="moreSearch">更多
            </el-button>
          </el-col>
        </el-row>
        <div style="clean:both"></div>
      </div>
      <div v-show="searchFlag" style="height: auto;margin-top: 10px;">
        <el-form ref="form" :model="listQuery.condition" label-width="80px" :inline="true">
          <el-form-item label=车架号:>
            <el-input type="textarea" :rows="2" style="width: 250px"
                      v-model="listQuery.condition.vin"  placeholder="请输入车架号"></el-input>
          </el-form-item>
          <el-form-item label="合格证状态" label-width="100px">
            <el-select v-model="listQuery.condition.certificatStatus" placeholder="请选择状态">
              <el-option label="未过滤" value=""></el-option>
              <!--<el-option label="未领取" value="10"></el-option>-->
              <el-option label="已领取" value="20"></el-option>
              <el-option label="已发放" value="30"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否入库" label-width="100px">
            <el-select v-model="listQuery.condition.isInbound" placeholder="请选择状态">
              <el-option label="是" value="Y"></el-option>
              <el-option label="否" value="N"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="领取时间:">
            <el-date-picker class="w200" v-model="listQuery.condition.receiveStartDate" type="datetime" placeholder="选择日期时间"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            align="right"></el-date-picker>
            <span class="zhi-font">至</span>
            <el-date-picker class="w200" v-model="listQuery.condition.receiveEndDate" type="datetime" placeholder="选择日期时间"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            align="right"></el-date-picker>
          </el-form-item>
          <el-form-item label="发放时间:">
            <el-date-picker class="w200" v-model="listQuery.condition.giveOutStartDate" type="datetime" placeholder="选择日期时间"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            align="right"></el-date-picker>
            <span class="zhi-font">至</span>
            <el-date-picker class="w200" v-model="listQuery.condition.giveOutEndDate" type="datetime" placeholder="选择日期时间"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            align="right"></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="search" style="margin-left: 10px">查询</el-button>
            <el-button type="primary" @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div style="clean:both"></div>
      <!--主列表-->
      <el-table ref="paymentTable" :data="tableData" v-loading="listLoading"
                element-loading-text="加载中" border fit highlight-current-row
                style="width: 100%;margin-top:5px;" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="40"></el-table-column>
        <el-table-column align="center" label="序号" width="50">
          <template slot-scope="scope">
            <span>{{scope.$index + 1}}</span>
          </template>
        </el-table-column>
        <el-table-column :key="key" align="center" :width="value.width" v-for='(value,key) in tableThead'
                         :label="value.title">
          <template slot-scope="scope">
            <div v-if="value.key === 'certificatStatus'">{{scope.row[value.key] | certificatStatusFilter}}</div>
            <div v-else>{{scope.row[value.key]}}</div>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <div v-show="!listLoading" class="pagination-container">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                       :current-page.sync="listQuery.current" :page-sizes="[10,20,30,50]" :page-size="listQuery.size"
                       layout="total, sizes, prev, pager, next, jumper" :total="listQuery.total">
        </el-pagination>
      </div>
    </div>
    <!--<div style="width: 2px;color:#000;margin-right: 10px;min-height:400px;height: 100%;"></div>-->
    <!--右-->
    <div style="flex: 1;">
      <div class="filter-container">
        <el-row>
          <el-col :span="24">
            <el-button type="primary" size="small" @click="updateStatus2('Y')">领取合格证书</el-button>
            <el-button type="primary" size="small" @click="updateStatus2('N')">发放合格证书</el-button>
          </el-col>
        </el-row>
      </div>
      <div>
        <el-form ref="sendMsgRef" :rules="rules" label-width="60px" style="margin: 6px 0 0 0" :model="sendMsgData">
          <!--#vin#-->
          <el-form-item prop="vin" label="车架号">
            <el-input type="textarea" autofocus="autofocus" :rows="6" v-model="sendMsgData.vin" id="vinId" ref="vinId"
                      placeholder="输入车架号,请以空行或回车换行隔开！" style="width: 220px"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script>
import * as certificateAPI from '@/api/certificate/certificate'
import waves from '@/directive/waves' // 水波纹指令
import * as Utils from '@/utils/index'
import { export_json_to_excel } from '@/vendor/Export2Excel'
const defautlTableThead = [
  // { key: 'id', title: '合格证id', width: '120' },
  { key: 'vin', title: '车架号', width: 180 },
  { key: 'certificatNum', title: '合格证数量', width: '120' },
  { key: 'receiveDate', title: '领取时间', width: '160' },
  { key: 'receiveUser', title: '领取人', width: '120' },
  { key: 'giveoutDate', title: '发放时间', width: '160' },
  { key: 'giveoutUser', title: '发放人', width: '' },
  { key: 'certificatStatus', title: '合格证状态', width: '120' },
  { key: 'inboundDate', title: '入库时间', width: '160' },
  { key: 'gmtCreated', title: '创建时间', width: '160' },
  { key: 'gmtModified', title: '修改时间', width: '160' },
  { key: 'storeHouseName', title: '仓库名称', width: '' },
  { key: 'stockId', title: '库存id', width: '120' },
  { key: 'remarks', title: '备注', width: '' }
]
export default {
  name: 'certificateMgt',
  directives: { waves },
  components: { },
  data() {
    return {
      tableThead: defautlTableThead,
      listQuery: {
        current: 1,
        size: 10,
        total: 0,
        condition: {
          isInbound: '',
          certificatStatus: null,
          vin: null,
          receiveStartDate: Utils.parseTime(new Date().getTime(), '{y}-{m}-{d} 00:00:00'),
          receiveEndDate: Utils.parseTime(new Date().getTime(), '{y}-{m}-{d} 23:59:59'),
          giveOutStartDate: null,
          giveOutEndDate: null
        }
      },
      tableData: [],
      listLoading: true,
      searchFlag: true,
      multipleSelection: [],
      downloadLoading: false,
      tHeader: [], // excel头
      filterVal: [], // excel字段
      filename: '合格证列表', // excel表名
      sendMsgData: {
        vin: ''
      },
      rules: {
        vin: [
          { required: true, message: '请输入车架号', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.initFunc()
  },
  methods: {
    // 导出-tHeader
    initFunc() {
      this.tHeader = []
      this.filterVal = []
      defautlTableThead.map((item) => {
        this.tHeader.push(item.title)
        this.filterVal.push(item.key)
      })
    },
    changeStatus() {
      return this.downloadData.map(v => {
        if (v.certificatStatus === '10') {
          v.certificatStatus = '未收取'
        } else if (v.certificatStatus === '20') {
          v.certificatStatus = '已收取'
        } else if (v.certificatStatus === '30') {
          v.certificatStatus = '已发放'
        }
        return v
      })
    },
    // 数据导出
    exportExcel() {
      const that = this
      const queryParam = {}
      if (this.$data.searchFlag) {
        queryParam.condition = this.$data.listQuery.condition
      } else {
        queryParam.condition = {}
      }
      this.downloadLoading = true
      certificateAPI.exportCertificationPage(queryParam).then(result => {
        this.downloadLoading = false
        if (result.code === 0) {
          this.downloadData = result.data
          if (this.downloadData.length) {
            const arr = this.changeStatus()
            require.ensure([], () => {
              const data = that.formatJson(that.filterVal, arr)
              export_json_to_excel(that.tHeader, data, that.filename)
            })
          }
        } else {
          this.$notify({
            title: '信息提示',
            message: result.message,
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    // 检查 数组 中单个 车架号 长度 是否是17位
    checkArrayVin(new_arr) {
      const that = this
      console.log('new_arr1', new_arr)
      if (new_arr.length > 0) {
        for (const k in new_arr) {
          if (new_arr[k].length !== 17) {
            that.$message({
              message: '输入的车架号中有不符合17位长度的车架号: ' + new_arr[k],
              type: 'warning',
              duration: 3000
            })
            return false
          }
        }
      }
      return true
    },
    // 更新合格证2
    updateStatus2(type) {
      const that = this
      let now_str = ''
      if (type === 'Y') {
        now_str = '领取'
        that.$refs['sendMsgRef'].validate(valid => {
          if (valid) {
            const vinStr = that.sendMsgData.vin
            if (vinStr.length < 17) {
              that.$message({
                message: '输入的车架号长度要大于等于17位',
                type: 'warning',
                duration: 3000
              })
            } else {
              const temp = vinStr.split(/[\n\r\s+,，；;]/g) // 字符串直接切割转数组，再对数组 进行处理
              let newStr = ''
              // console.log('temp1', temp)
              // temp = vinStr.replace(/[\r\s+,，；;]/g, '') // 中英文逗号 换行 中英文分隔符
              for (let i = 0; i < temp.length; i++) {
                if (temp[i] === '') {
                  // 删除数组中空值
                  temp.splice(i, 1)
                  i--
                }
              }
              // console.log('temp2', temp)
              if (that.checkArrayVin(temp)) {
                newStr = temp.length > 1 ? temp.join('\n') : temp[0]
                console.log('输出的用于提交的vin字符串', newStr)
                const toParams = {
                  vin: newStr,
                  handleType: type
                }
                certificateAPI.updateCertification(toParams).then(result => {
                  that.$message({
                    message: now_str + '成功',
                    type: 'success',
                    duration: 3000
                  })
                  that.resetSearch()
                }).catch(() => {
                  that.getList()
                })
              }
            }
          }
        })
      } else if (type === 'N') {
        now_str = '发放'
        if (that.checkSelect(that.multipleSelection)) {
          this.$confirm('您确定' + now_str + '合格证?', '提示', {
            confirmButtonText: '确定',
            showCancelButton: false,
            type: 'warning'
          }).then(() => {
            const ids1 = []
            const ids2 = []
            that.multipleSelection.map(item => {
              ids1.push(item.vin)
              ids2.push(item.id)
            })
            const vins = ids1.length > 1 ? ids1.join(',') : ids1[0]
            const certificationIds = ids2.length > 1 ? ids2.join(',') : ids2[0]
            certificateAPI.updateCertification({ vin: vins, handleType: type, certificationId: certificationIds }).then(result => {
              that.$message({
                message: now_str + '成功',
                type: 'success',
                duration: 3000
              })
              that.getList()
            })
          })
        }
      }
    },
    getList() {
      // 列表查询
      this.listLoading = true
      // 处理是否展开更多
      let queryParam = {}
      if (this.searchFlag) {
        // this.listQuery.condition.storeHouseId = this.$store.getters.currentStorehouse.id
        queryParam = this.listQuery
      } else {
        Object.assign(queryParam, this.listQuery)
        queryParam.condition = {
          receiveStartDate: Utils.parseTime(new Date().getTime(), '{y}-{m}-{d} 00:00:00'),
          receiveEndDate: Utils.parseTime(new Date().getTime(), '{y}-{m}-{d} 23:59:59'),
          vin: this.listQuery.condition.vin,
          // storeHouseId: this.$store.getters.currentStorehouse.id
          giveOutStartDate: null,
          giveOutEndDate: null
        }
      }
      certificateAPI.queryCertificationPage(queryParam).then(result => {
        if (result.code === 0) {
          this.tableData = result.data.records
          this.listQuery.total = result.data.total
        } else {
          this.$message({
            title: '信息提示',
            message: result.message,
            type: 'error',
            duration: 2000
          })
        }
        this.listLoading = false
      })
      setTimeout(() => {
        this.$refs.vinId.focus()
      }, 300)
      // document.getElementById('vinId').focus() // 自动获取焦点
    },
    // 更多
    moreSearch() {
      this.searchFlag = !this.searchFlag
    },
    // 查询
    search() {
      this.listQuery.current = 1
      this.listQuery.size = 10
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.size = val
      this.listQuery.current = 1
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.current = val
      this.getList()
    },
    // 重置
    resetSearch() {
      this.listQuery.current = 1
      this.listQuery.size = 10
      this.listQuery.condition = {
        isInbound: '',
        certificatStatus: null,
        vin: null,
        receiveStartDate: null,
        receiveEndDate: null,
        giveOutStartDate: null,
        giveOutEndDate: null
      }
      this.multipleSelection = []
      this.sendMsgData.vin = ''
      this.getList()
    },
    // 检查是否选择单条
    checkSelect(data) {
      const l = data.length
      if (l === 0) {
        this.$message({
          message: '未选择',
          type: 'warning',
          duration: 2000
        })
        return false
      }
      return true
    },
    // 表格改变时
    handleSelectionChange(val) {
      this.multipleSelection = val
      this.sendMsgData.vin = ''
      const ids = []
      this.multipleSelection.map(item => {
        ids.push(item.vin)
      })
      this.sendMsgData.vin = ids.length > 1 ? ids.join('\n') : ids[0]
    }
  }
}
</script>

<style scope>
</style>
